package com.gzdh.tang.modu.job;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.modu.entity.AliFaceOrders;
import com.gzdh.tang.modu.entity.Fk;
import com.gzdh.tang.modu.entity.MacMainpSbruan;
import com.gzdh.tang.modu.entity.Reserve;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.AliFaceOrdersService;
import com.gzdh.tang.modu.service.FkService;
import com.gzdh.tang.modu.service.MacMainpSbruanService;
import com.gzdh.tang.modu.service.ReserveService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//@JobHandler(value = "ALiOrderJobHandler")
@Component
public class ALiOrderJob {


    @Autowired
    AliFaceOrdersService aliFaceOrdersService;

    @Autowired
    FkService fkService;

    @Autowired
    ReserveService reserveService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    private List<MacMainpSbruan> macMainpSbruanList;

    private int i = 0;
    private Date date = new Date();

    @XxlJob("ALiOrderJobHandler")
    public void ALiOrderJobHandler() throws Exception {
        macMainpSbruanList = macMainpSbruanService.list();
        //将未上传的数据筛选出来
        List<AliFaceOrders> aliFaceOrdersList = aliFaceOrdersService.list(
                new QueryWrapper<AliFaceOrders>().lambda().eq(AliFaceOrders::getHavePost, false)
        );
        for (AliFaceOrders goo : aliFaceOrdersList) {
//            date = new Date();
            date = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(goo.getOrders().substring(0, goo.getOrders().length() - 1));
            tAliFaceOrder(goo);
        }

    }

//
//    public ReturnT<String> execute(String s) throws Exception {
//
//        macMainpSbruanList = macMainpSbruanService.list();
//        //将未上传的数据筛选出来
//        List<AliFaceOrders> aliFaceOrdersList = aliFaceOrdersService.list(
//                new QueryWrapper<AliFaceOrders>().lambda().eq(AliFaceOrders::getHavePost, false)
//        );
//        for (AliFaceOrders goo : aliFaceOrdersList) {
////            BigDecimal youhuiPrice = new BigDecimal(goo.getYouhuiPrice());
////            BigDecimal orderPrice = youhuiPrice.add(new BigDecimal(goo.getPrice()));
////            BigDecimal fkPrice = youhuiPrice.add(new BigDecimal(goo.getFkPrice()));
////            goo.setPrice(orderPrice.toPlainString());
////            goo.setFkPrice(fkPrice.toPlainString());
//            tAliFaceOrder(goo);
//        }
//        return SUCCESS;
//    }

    private void tAliFaceOrder(AliFaceOrders aliFaceOrders) {
        if (aliFaceOrders.getState()) {
            //已经扣款成功，只负责上报
            Boolean haveState = havePost(aliFaceOrders.getOrders(), aliFaceOrders.getPrice(),
                    aliFaceOrders.getAuthCode(), aliFaceOrders.getAliAgreementNo(),
                    aliFaceOrders.getPrice(), aliFaceOrders.getTerminalParams(), aliFaceOrders.getYouhuiPrice());
            aliFaceOrders.setHaveState(haveState);
            aliFaceOrders.setHavePost(haveState);
            aliFaceOrdersService.updateById(aliFaceOrders);

        } else {
            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, aliFaceOrders.getCardno()));
            if (new BigDecimal(fk.getKye()).compareTo(new BigDecimal(0)) == 1) {
                aliFaceOrders.setFkPrice(new BigDecimal(fk.getKye()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            } else {
                aliFaceOrders.setFkPrice("0");
            }
            aliFaceOrdersService.updateById(aliFaceOrders);
            boolean status = false;
            if (StringUtils.isNotEmpty(aliFaceOrders.getAuthCode())) {
                if (new BigDecimal(aliFaceOrders.getPrice()).compareTo(new BigDecimal(aliFaceOrders.getFkPrice())) == 1) {
                    status = havePost(aliFaceOrders.getOrders(),
                            aliFaceOrders.getPrice(), aliFaceOrders.getAuthCode(),
                            aliFaceOrders.getAliAgreementNo(), aliFaceOrders.getFkPrice(), aliFaceOrders.getTerminalParams(), aliFaceOrders.getYouhuiPrice());
                } else {
                    status = havePost(aliFaceOrders.getOrders(),
                            aliFaceOrders.getPrice(), aliFaceOrders.getAuthCode(),
                            aliFaceOrders.getAliAgreementNo(), aliFaceOrders.getPrice(), aliFaceOrders.getTerminalParams(), aliFaceOrders.getYouhuiPrice());
                }
            }                //写FK表
            MacMainpSbruan
                    macMainpSbruan = macMainpSbruanList.stream().filter(macMainpSbruan1 -> aliFaceOrders.getDeviceId().equals(macMainpSbruan1.getMac()))
                    .findFirst().orElse(new MacMainpSbruan());
            BigDecimal aliPrice = new BigDecimal(aliFaceOrders.getPrice()).subtract(new BigDecimal(aliFaceOrders.getFkPrice()));
            BigDecimal fksPrice = new BigDecimal(aliFaceOrders.getFkPrice());
            if (aliPrice.compareTo(new BigDecimal(0)) == -1) {
                fksPrice = new BigDecimal(aliFaceOrders.getPrice());
            }
            if (status) {
//            if (new BigDecimal(fk.getBtye()).compareTo(new BigDecimal(0)) == 1) {
//                fksPrice = new BigDecimal(aliFaceOrders.getFkPrice()).subtract(new BigDecimal(fk.getBtye()));
//                saveReserve(aliFaceOrders, fk, macMainpSbruan, String.valueOf(fk.getBtye()), "1");
//            }
                if (new BigDecimal(fk.getKye()).compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, fksPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(), "0");
                }
                if (new BigDecimal(aliFaceOrders.getYouhuiPrice()).compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, aliFaceOrders.getYouhuiPrice(), "1");
                }
                if (aliPrice.compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, aliPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(), "4");
                }
            } else {
                //代扣失败
                if (new BigDecimal(fk.getKye()).compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, fksPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(), "0");
                }
                if (new BigDecimal(aliFaceOrders.getYouhuiPrice()).compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, aliFaceOrders.getYouhuiPrice(), "1");
                }
                if (aliPrice.compareTo(new BigDecimal(0)) == 1) {
                    saveReserve(aliFaceOrders, fk, macMainpSbruan, aliPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(), "0");
                }
            }
            aliFaceOrders.setHaveState(true);
            aliFaceOrders.setHavePost(true);
            aliFaceOrdersService.updateById(aliFaceOrders);
        }
    }

    //上报方法
    private boolean havePost(String orders, String orderPrice,
                             String authCode, String agreementNo,
                             String fkPrice, String terminalParams, String youhuiPrice) {
        try {
            BigDecimal youhuiPriceBig = new BigDecimal(youhuiPrice);
            BigDecimal orderPriceBig = new BigDecimal(orderPrice).add(youhuiPriceBig);
            BigDecimal fkPriceBig = new BigDecimal(fkPrice).add(youhuiPriceBig);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
                    "json", "GBK", AliPayUtil.getPublicKey(),
                    "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean;

            if (StringUtils.isEmpty(agreementNo)) {
                jsonsRootBean = new JsonsRootBean(orders, orderPriceBig.toPlainString(),
                        authCode, AliPayUtil.getAssignJointAccountId(), fkPriceBig.toPlainString(), terminalParams);
            } else {
                jsonsRootBean = new JsonsRootBean(orders, orderPriceBig.toPlainString(),
                        authCode, agreementNo, AliPayUtil.getAssignJointAccountId(), fkPriceBig.toPlainString(), terminalParams);
            }
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
            if (response.isSuccess()) {
                System.out.println("调用成功");
                return true;
            } else {
                System.out.println("调用失败");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void saveReserve(AliFaceOrders aliFaceOrders, Fk fk,
                             MacMainpSbruan macMainpSbruan,
                             String price, String sc) {
        date = new Date(date.getTime() + (i++ * 10));
        Reserve reserve = new Reserve();
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(fk.getBqh());
        reserve.setKsh(fk.getKsh());
        reserve.setDinner(aliFaceOrders.getDinner());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(aliFaceOrders.getDinner());
        reserve.setCode(macMainpSbruan.getCode());
        reserve.setSl(1);
        reserve.setJe(price);
        try {
            reserve.setYe("0");
        } catch (Exception e) {
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(aliFaceOrders.getTradeNo());
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(date));
        reserve.setHname("现金菜");
        reserve.setSddz(aliFaceOrders.getDeviceId());
        reserve.setCs(0);
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(aliFaceOrders.getOrders());
        reserve.setAddr(macMainpSbruan.getAddr());
        reserveService.save(reserve);
    }
}
